﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fcom.VNInsurance.Web.CultureHelper;
using System.IO;
using Fcom.VNInsurance.Web.Models;
namespace Fcom.VNInsurance.Web.Controllers
{

    public class ProductController : CultureController
    {
        //
        // GET: /Product/
        VNInsurance.Web.Models.VNInsuranceDataContext db = new Models.VNInsuranceDataContext();
        public ActionResult Index()
        {
            return View();
        }
        //MNCatDetail
        [Authorize(Roles = "13,14")]
        public ActionResult MNCatDetail(int CatID)
        
        {
            var catproduct = db.ProductCats.Where(m => m.ID == CatID).FirstOrDefault();
            ViewBag.CatProduct = catproduct;
            var productLang = db.ProductLangs.Where(m => m.Product.CatID == CatID && m.LangID == Request.Cookies["_culture"]["lang"]);
            return View(productLang);
        }
        //ProductCatList

        public ActionResult ProductCatList(int CatID)
        {
            var catproduct = db.ProductCats.Where(m => m.ID == CatID).FirstOrDefault();
            ViewBag.CatProduct = catproduct;
            var productLang = db.ProductLangs.Where(m => m.Product.CatID == CatID && m.LangID == Request.Cookies["_culture"]["lang"]);
            ViewBag.news = db.NewsLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"] && n.New.NCatID == 1);
            return View(productLang);
        }
        //MNProductDetail
         [Authorize(Roles = "13,14")]
        [HttpGet]
        public ActionResult MNProductDetail(int ProductID)
        {
            var productLang = db.ProductLangs.Where(m => m.ProductID==ProductID && m.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangProduct = productLang;
            var catproduct = db.ProductCats.Where(m => m.ID == productLang.Product.CatID).FirstOrDefault();
            ViewBag.CatProduct = catproduct;
            ViewBag.Product = productLang.Product;
            ViewBag.ProductFaqs = db.ProductFAQs.Where(p => p.LangID == Request.Cookies["_culture"]["lang"] && p.ProductID == ProductID);
            return View();
        }
        //MNProductDetail
         [Authorize(Roles = "13,14")]
        [HttpGet]
        public ActionResult MNFaq(int ProductID)
        {
            var productLang = db.ProductLangs.Where(m => m.ProductID == ProductID && m.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangProduct = productLang;
            var catproduct = db.ProductCats.Where(m => m.ID == productLang.Product.CatID).FirstOrDefault();
            ViewBag.CatProduct = catproduct;
            ViewBag.Product = productLang.Product;
            return View();
        }
        public ActionResult GetJsonFaqProduct(int ID)
        {
            var faqs = from p in db.ProductFAQs
                       where p.LangID == Request.Cookies["_culture"]["lang"] && p.ProductID == ID
                       select new { 
                           p.ID,p.Question
                       };

            return Json(faqs,JsonRequestBehavior.AllowGet);
        }
        //public ActionResult MNProductDetail(int ProductID)
        [HttpPost, ValidateInput(false)]
        public ActionResult MNProductDetail(bool ckLink,string ProductLink,string PIcon,Fcom.VNInsurance.Web.ViewModel.ProductInfo model)
        {
            if (ModelState.IsValid)
            {
                var searchp = db.Products.Where(p => p.ID == model.ProductID).FirstOrDefault();
                searchp.ProductBaner = model.Banner;
                var productlang = db.ProductLangs.Where(m => m.ProductID == model.ProductID && m.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
                productlang.DisplayIntro = HttpUtility.HtmlEncode(model.Fullintro);
                productlang.DisplayName = model.ProductName;
                productlang.SmallIntro = model.SmallIntro;
                productlang.Product.ProductIcon = PIcon;
                productlang.Product.toOtherlink = ckLink;
                productlang.Product.Ortherlink = ProductLink;
                db.SubmitChanges();
                return RedirectToAction("MNCatDetail", new { CatID = productlang.Product.CatID });
            }
            var productLang = db.ProductLangs.Where(m => m.ProductID == model.ProductID && m.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangProduct = productLang;
            var catproduct = db.ProductCats.Where(m => m.ID == productLang.Product.CatID).FirstOrDefault();
            ViewBag.CatProduct = catproduct;
            ViewBag.Product = productLang.Product;
            ViewBag.ProductFaqs = db.ProductFAQs.Where(p => p.LangID == Request.Cookies["_culture"]["lang"] && p.ProductID == model.ProductID);
            return View();
        }
        //ajAddFaq
        // ProductID: $("#txtproductid").val(), question: $("#Question").val(), answer: $("#AnswerQuest").val()
         [HttpPost]
        public JsonResult ajAddFaq(int ProductID,string question,string answer)
        {
            Fcom.VNInsurance.Web.Models.ProductFAQ productfaq = new Models.ProductFAQ();
            productfaq.LangID = Request.Cookies["_culture"]["lang"];
            productfaq.ProductID = ProductID;
            productfaq.Question = question;
            productfaq.Answer = answer;
            db.ProductFAQs.InsertOnSubmit(productfaq);
            db.SubmitChanges();
            return Json(new { success=true,ID=productfaq.ID,Question=productfaq.Question,Answer=productfaq.Answer,ProductID=productfaq.ProductID});
        }
         [HttpPost]
         public JsonResult ajDeleteFaq(int FaqIDd)
         {
             var productfaq = db.ProductFAQs.Where(m => m.ID == FaqIDd).FirstOrDefault();

             db.ProductFAQs.DeleteOnSubmit(productfaq);
             db.SubmitChanges();
             return Json(new { success = true});
         }
         [HttpPost]
         public JsonResult ajEditFaq(int FaqID, string question, string answer)
         {
             var productfaq = db.ProductFAQs.Where(m=>m.ID==FaqID).FirstOrDefault();
                  
             productfaq.Question = question;
             productfaq.Answer = answer;
             db.SubmitChanges();
             return Json(new { success = true, ID = productfaq.ID, Question = productfaq.Question, Answer = productfaq.Answer, ProductID = productfaq.ProductID });
         }
         public ActionResult EditFaq(int ID)
         {
             var productfaq = db.ProductFAQs.Where(m => m.ID == ID).FirstOrDefault();
             productfaq.Answer = HttpUtility.HtmlDecode(productfaq.Answer);
             return View(productfaq);
         }
        [HttpPost,ValidateInput(false)]
         public ActionResult EditFaq(Fcom.VNInsurance.Web.Models.ProductFAQ model)
         {
             if (ModelState.IsValid)
             {
                 var productfaq = db.ProductFAQs.Where(m => m.ID == model.ID).FirstOrDefault();
                 productfaq.Question = model.Question;
                 productfaq.Answer = HttpUtility.HtmlEncode(model.Answer);
                 db.SubmitChanges();
                 return RedirectToAction("MNFaq", new { ProductID = productfaq.ProductID });
             }
             return View();
         }
         [Authorize(Roles = "13,14")]
        public ActionResult AddFaq(int ID)
        {
            ViewBag.Product= db.ProductLangs.Where(m => m.ProductID == ID && m.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            return View();
        }
        [HttpPost, ValidateInput(false)]
        public ActionResult AddFaq(int ProductID,Fcom.VNInsurance.Web.Models.ProductFAQ model)
        {
            if (ModelState.IsValid)
            {
                Fcom.VNInsurance.Web.Models.ProductFAQ productfaq = new Models.ProductFAQ();
                productfaq.ProductID = ProductID;
                productfaq.LangID = Request.Cookies["_culture"]["lang"];        
                productfaq.Question = model.Question;
                productfaq.Answer = HttpUtility.HtmlEncode(model.Answer);
                db.ProductFAQs.InsertOnSubmit(productfaq);
                db.SubmitChanges();
                return RedirectToAction("MNFaq", new { ProductID = productfaq.ProductID });
            }
            return View();
        }
        //GetJsonProductBanner
        public JsonResult GetJsonProductBanner()
        {
            string serverPath = Server.MapPath("~/Content/images/ProductBaner");
            DirectoryInfo d = new DirectoryInfo(serverPath);
            List<Fcom.VNInsurance.Web.ViewModel.FileInfo> listf = new List<Fcom.VNInsurance.Web.ViewModel.FileInfo>();
            Fcom.VNInsurance.Web.ViewModel.FileInfo f;
            int i = 1;
            foreach (FileInfo ff in d.GetFiles())
            {
                f = new ViewModel.FileInfo();
                f.FileName = ff.Name;
                f.STT = i;
                i += 1;
                listf.Add(f);
                
            }
            
            return Json(listf, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult UploadBanner(string qqFile)
        {
            // The upload action will be called by the client control
            // for each file that was selected by the user for upload

            var path = Server.MapPath("~/Content/images/ProductBaner");
            qqFile=DateTime.Now.ToString("yyyyMMddHHmmssffff") + qqFile.Replace(" ", "-");
            var file = Path.Combine(path, qqFile);
            using (var output = System.IO.File.Create(file))
            {
                Request.InputStream.CopyTo(output);
            }

            return Json(new { success = true, newfilename = qqFile });
        

        }
        public JsonResult DeleteBanner(string spath)
        {
            string serverPath = Server.MapPath("~/Content/images/ProductBaner/" + spath);
            FileInfo fi = new FileInfo(serverPath);

            if (fi.Exists)
            {
                if (fi.Extension == ".js" || fi.Extension == ".css")
                    return Json(new { msg = "You dont have permission to delete this file!", status = false }, JsonRequestBehavior.AllowGet);
                try
                {
                    fi.Delete();
                                   }
                catch
                {
                    return Json(new { msg = "Can't delete this file!", status = false }, JsonRequestBehavior.AllowGet);
                }
                return Json(new { status = true }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { msg = "File don't exists!", status = false }, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult ProductDetail(int pID,string step)
        {
            if (Session["clInfo"] != null&&step!="1")
            {
                return RedirectToAction("Compare", new { pID = pID });
            }

            var LangProduct = db.ProductLangs.Where(p => p.ProductID == pID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            var LangCatProduct = db.ProductCatLangs.Where(p => p.CatID == LangProduct.Product.ProductCat.ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangCat = LangCatProduct;
            return View(LangProduct);
        }
        [HttpPost]
        public ActionResult SaveInfo(Fcom.VNInsurance.Web.Models.clInfo model)
        {
            if (ModelState.IsValid)
            {
                Session["clInfo"] = model;
            }
            return RedirectToAction("Compare", new { pID=model.ProductID});
        }
        public ActionResult Compare(int ID)
        {


            var LangProduct = db.ProductLangs.Where(p => p.ProductID ==ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangProduct = LangProduct;
            var LangCatProduct = db.ProductCatLangs.Where(p => p.CatID == LangProduct.Product.ProductCat.ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
            ViewBag.LangCat = LangCatProduct;
            ViewBag.productFAQ = db.ProductFAQs.Where(p => p.LangID == Request.Cookies["_culture"]["lang"] && p.ProductID == ID);
            var LangCPProduct = from cp in db.CompanyProductLangs
                                where cp.LangID == Request.Cookies["_culture"]["lang"] && cp.CompanyProduct.ProductID == ID
                                select new Fcom.VNInsurance.Web.Models.CPInfo() { CProductID = cp.CProductID, ProductName = cp.DisplayName, CompanyName = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyName, CompanyLogo = cp.CompanyProduct.Company.CompanyLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault().CompanyLogo, Benefit = cp.Benefit, Future = cp.Future, MoreInfo = cp.Moreinfo, Fare = cp.OneFare, InsuranceMoney = cp.InsuranceMoney };
            ViewBag.CurrentLang = LangProduct.Language;
            return View(LangCPProduct);
        }
        public ActionResult Policy(int cpID)
        {
           
            var LangCProduct = (from cp in db.CompanyProductLangs
                                where cp.LangID == Request.Cookies["_culture"]["lang"] && cp.CProductID == cpID
                                select new Fcom.VNInsurance.Web.Models.CPInfo() { CProductID = cp.CProductID, ProductName = cp.DisplayName, CompanyName = cp.CompanyProduct.Company.CompanyName, CompanyLogo = cp.CompanyProduct.Company.CompanyLogo, Benefit = cp.Benefit, Future = cp.Future, MoreInfo = cp.Moreinfo, Fare=cp.OneFare,ProductID=cp.CompanyProduct.ProductID,Intro=cp.Intro,email=cp.CompanyProduct.Company.Email,address=cp.CompanyProduct.Company.Address}).FirstOrDefault();
            if (LangCProduct == null)
            {
                return View("Error");
            }
            else{
                if (Session["clInfo"] == null)
                    return RedirectToAction("ProductDetail", new { pID = LangCProduct.ProductID });
                var LangProduct = db.ProductLangs.Where(p => p.ProductID == LangCProduct.ProductID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
                var Product = LangProduct.Product;
                var LangCatProduct = db.ProductCatLangs.Where(p => p.CatID == LangProduct.Product.ProductCat.ID && p.LangID == Request.Cookies["_culture"]["lang"]).FirstOrDefault();
                ViewBag.LangCat = LangCatProduct;
                ViewBag.LangProduct = LangProduct;
                ViewBag.BaseProduct = Product;
                ViewBag.CurrentLang = LangProduct.Language;
                return View(LangCProduct);
            }
        }
        [HttpPost]
        public ActionResult PolicySave(int joinnumber, int cproductid)
        {

            return RedirectToAction("Finished");
        }
        public ActionResult Finished()
        {
            return View();
        }
        public ActionResult ajChangeCatColor(int CatID, string color)
        {
            var productcat = db.ProductCats.Where(m => m.ID == CatID).FirstOrDefault();
            productcat.CatColor = color;
            db.SubmitChanges();
            return Json(new { success=true});
        }
        #region PackageProduct
        public ActionResult MNPackage(int ID)
        {
            var package = db.PackageBenefits.Where(m=>m.PackageProduct.ProductID==ID);
            ViewBag.ID = ID;
             return View();
        }
        public ActionResult GetJsonPackage(int id)
        {
            var lang = Request.Cookies["_culture"]["lang"];
            var kage = from s in db.PackageProducts where s.ProductID == id select new { s.ID, s.Package.PackageLangs.Where(m => m.LangID == lang).SingleOrDefault().DisplayNamePackage, s.Product.ProductLangs.Where(m => m.LangID == lang).SingleOrDefault().DisplayName };
            //new { s.BenefitID, s.Benefit.BenefitLangs.Where(m=>m.LangID==lang).SingleOrDefault().DisplayName,s.PackageProduct.PackageID,s.PackageProduct.Package.PackageLangs.Where(m=>m.LangID==lang).Single().DisplayNamePackage,s.InputKey};
            return Json(kage, JsonRequestBehavior.AllowGet);
        }
        public ActionResult AddPackageProduct(int id)
        {
            var lang=Request.Cookies["_culture"]["lang"];
            ViewBag.package = db.PackageLangs.Where(m => m.LangID == lang);
            ViewBag.ID = id;
            ViewBag.ProductName = db.ProductLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"] && m.ProductID == id).SingleOrDefault().DisplayName;
            return View();
        }
        [HttpPost]
        public ActionResult AddPackageProduct(PackageProduct packagepro)
        {
            var lang = Request.Cookies["_culture"]["lang"];
            ViewBag.package = db.PackageLangs.Where(m => m.LangID == lang);
            ViewBag.ID = packagepro.ProductID;
            ViewBag.ProductName = db.ProductLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"] && m.ProductID ==packagepro.ProductID).SingleOrDefault().DisplayName;
            try
            {
                
                 var findpackageid=(from a in db.PackageProducts where a.ProductID==packagepro.ProductID&& a.PackageID==packagepro.PackageID select a).FirstOrDefault();
                 if (findpackageid == null)
                 {
                     PackageProduct pkpro = new PackageProduct();
                     pkpro.ProductID = packagepro.ProductID;
                     pkpro.PackageID = packagepro.PackageID;
                     db.PackageProducts.InsertOnSubmit(pkpro);
                     db.SubmitChanges();
                 }
                 return RedirectToAction("MNPackage", new { id = packagepro.ProductID });
            }
            catch
            {
                return View(packagepro);
            }
        }
        public ActionResult EditPackageProduct(int id)
        {
            var lang = Request.Cookies["_culture"]["lang"];
            var product = db.PackageProducts.Where(m => m.ID == id).FirstOrDefault();
            ViewBag.package = db.PackageLangs.Where(m => m.LangID == lang);
            ViewBag.ProductName = db.ProductLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"] && m.ProductID == product.ProductID).SingleOrDefault().DisplayName;
            return View(product);
        }
        [HttpPost]
        public ActionResult EditPackageProduct(PackageProduct packagepro)
        {
            var lang = Request.Cookies["_culture"]["lang"];
            ViewBag.package = db.PackageLangs.Where(m => m.LangID == lang);
            ViewBag.ProductName = db.ProductLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"] && m.ProductID == packagepro.ProductID).SingleOrDefault().DisplayName;
            var product = db.PackageProducts.Where(m => m.ID == packagepro.ID).FirstOrDefault();
            if (product != null)
            {
                var exit = db.PackageProducts.Where(m => m.PackageID == packagepro.PackageID).FirstOrDefault();
                if (exit == null)
                {
                    product.PackageID = packagepro.PackageID;
                    db.SubmitChanges();
                   
                }
                return RedirectToAction("MNPackage", new { id = packagepro.ProductID });
                
            }
            else
            {
                return View(packagepro);
            }
        }
        public ActionResult DeletePackageProduct(int id)
        {
            try
            {
                var packagepro = db.PackageProducts.Where(m => m.ID == id).FirstOrDefault();
                var packagebenefit = db.PackageBenefits.Where(m => m.ProductPackageID == packagepro.ID);
                db.PackageBenefits.DeleteAllOnSubmit(packagebenefit);
                db.PackageProducts.DeleteOnSubmit(packagepro);
                db.SubmitChanges();
                return Json("Success");
            }
            catch
            {
                return Json("Fail");
            }
        }
        #endregion PackageProduct

        #region PackageBenefit
        public ActionResult MNPackageBenefit(int id)
        {
            ViewBag.ProductName = db.ProductLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"] && m.ProductID == id).SingleOrDefault().DisplayName;
            ViewBag.id = id;
            return View();
        }
       
        public ActionResult GetJsonPackageBenefit(int id)
        {
            var lang = Request.Cookies["_culture"]["lang"];
            var kage = from s in db.PackageBenefits where s.ProductPackageID == id select new { s.ID, s.Benefit.BenefitLangs.Where(m => m.LangID == lang).SingleOrDefault().DisplayName, s.PackageProduct.Package.PackageLangs.Where(m => m.LangID == lang).Single().DisplayNamePackage, s.InputKey,s.Liability};
            return Json(kage, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public ActionResult AddPackageBenefit(int id)
        {
            var lang = Request.Cookies["_culture"]["lang"];
            List<Fcom.VNInsurance.Web.Models.BenefitLang> dba=new List<BenefitLang>();
            List<Fcom.VNInsurance.Web.Models.BenefitLang> dbb=db.BenefitLangs.Where(m=>m.LangID==lang).ToList();
            foreach (var a in db.PackageBenefits)
            {
                if (a.ProductPackageID == id)
                {
                    foreach (var b in db.BenefitLangs)
                    {
                        if (b.LangID == lang && b.BenefitID == a.BenefitID)
                        {

                            dba.Add(b);
                        }
                    }
                }
            }
           foreach(var c in dba)
           {
               dbb.Remove(c);
           }
            ViewBag.Benefit =dbb;
            ViewBag.id = id;
            return View();
        }
        [HttpPost]
        public ActionResult AddPackageBenefit(PackageBenefit packagebenefit)
        {
            var find = db.PackageBenefits.Where(m => m.ProductPackageID == packagebenefit.ProductPackageID && m.BenefitID == packagebenefit.BenefitID).FirstOrDefault();
            if (find == null)
            {
                var lang = Request.Cookies["_culture"]["lang"];
                PackageBenefit pk = new PackageBenefit();
                PackageBenefit pk2 = new PackageBenefit();
                PackageBenefit pk3 = new PackageBenefit();
                pk.InputKey = packagebenefit.InputKey;
                pk.ProductPackageID = packagebenefit.ProductPackageID;
                pk.BenefitID = packagebenefit.BenefitID;
                pk.Liability = packagebenefit.Liability;

                pk2.InputKey = packagebenefit.InputKey;
                pk2.ProductPackageID = db.PackageProducts.Where(m => m.ID != packagebenefit.ProductPackageID).First().ID;
                pk2.BenefitID = packagebenefit.BenefitID;
                pk2.Liability = packagebenefit.Liability;

                pk3.InputKey = packagebenefit.InputKey;
                var last = db.PackageProducts.Where(m => m.ID != packagebenefit.ProductPackageID).ToList();
                pk3.ProductPackageID = last.Last().ID;

                pk3.BenefitID = packagebenefit.BenefitID;
                pk3.Liability = packagebenefit.Liability;

                db.PackageBenefits.InsertOnSubmit(pk);
                db.PackageBenefits.InsertOnSubmit(pk2);
                db.PackageBenefits.InsertOnSubmit(pk3);
                db.SubmitChanges();
                return RedirectToAction("MNPackageBenefit", new { id = packagebenefit.ProductPackageID });
            }
            else
            {
                return RedirectToAction("MNPackageBenefit", new { id = packagebenefit.ProductPackageID });
            }
        }
        public ActionResult EditPackageBenefit(int id)
        {
            var pakage = db.PackageBenefits.Where(m => m.ID == id).FirstOrDefault();
            var lang = Request.Cookies["_culture"]["lang"];    
            ViewBag.Benefit = db.BenefitLangs.Where(m=>m.LangID==lang);
            return View(pakage);
        }
        [HttpPost]
        public ActionResult EditPackageBenefit(PackageBenefit packagebenefit)
        {
            var find = db.PackageBenefits.Where(m => m.ID == packagebenefit.ID).FirstOrDefault();
            var exit = db.PackageBenefits.Where(m => m.BenefitID == packagebenefit.BenefitID).FirstOrDefault();
            if (exit == null)
            {
                find.BenefitID = packagebenefit.BenefitID;
                
                db.SubmitChanges();

            }
            find.InputKey = packagebenefit.InputKey;
            find.Liability = packagebenefit.Liability;
            db.SubmitChanges();
            return RedirectToAction("MNPackageBenefit", new { id = packagebenefit.ProductPackageID });
        }
        public ActionResult DeletePackageBenefit(int id)
        {
            try
            {
                var packagepro = db.PackageBenefits.Where(m => m.ID == id).FirstOrDefault();
                db.PackageBenefits.DeleteOnSubmit(packagepro);
                db.SubmitChanges();
                return Json("Success");
            }
            catch
            {
                return Json("Fail");
            }
        }
        #endregion PackageBenefit
    }
}
